package com.sdkj.fixed.asset.assets.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.BorrowIssueExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.in_vo.SignatureParam;
import com.sdkj.fixed.asset.api.assets.out_vo.UserInfo;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.JpushClientUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.PushManagement;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author niuliwei
 * @descriptionn 资产借用与归还
 * @date 2020/7/23 16:26
 */
@Service
public class BorowService extends BaseService<BorrowIssue> {
    Logger log = LoggerFactory.getLogger(BorowService.class);
    @Autowired
    private BorrowIssueMapper borrowIssueMapper;
    @Autowired
    private BorrowIssueAssetsMapper borrowIssueAssetsMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private AssetLogMapper assetLogMapper;
    @Autowired
    private BorrowApplyAssetsMapper borrowApplyAssetsMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private AssetReportService assetReportService;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    @Autowired
    private AssetReportMapper assetReportMapper;
    @Autowired
    private PushManagementMapper pushMapper;

    @Override
    public BaseMapper getMapper() {
        return borrowIssueMapper;
    }

    //获取订单号
    private String getNumber(String key, String orgId) {
        Long incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        if (incr == 0) {
            incr = redisUtil.getIncr(key +"_"+ orgId +"_"+ DateTools.dateToString(new Date(), "yyyyMMdd"), DateTools.expiresTime());
        }
        DecimalFormat df = new DecimalFormat("0000");
        return key + DateTools.dateToString(new Date(), "yyyyMMdd") + df.format(incr);
    }

    /**
     * 新增
     * @param param
     * @return
     */
    public BorrowIssue add(BorrowIssueExtend param){


        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        param.setNumber(getNumber("JY", orgId));
        param.setBorrowBackState(1);
        param.setState(1);
        param.setIsDeleted(0);
        param.setCreateUser(userId);
        param.setCreateDate(TimeTool.getCurrentTimeStr());
        param.setUpdateUser(userId);
        param.setUpdateDate(TimeTool.getCurrentTimeStr());
        param.setOrgId(orgId);
        borrowIssueMapper.insertSelective(param);

        historyMapper.batchInsert(param.getAssetIdList() ,param.getId(),3);

        for (String str:param.getAssetIdList()) {

            if(!redisUtil.setnx(str,1800)){
                throw new LogicException("请核对资产状态是否发生改变");
            }

            BorrowIssueAssets asset = new BorrowIssueAssets();
            asset.setBorrowIssueId(param.getId());
            asset.setAssetId(str);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());
            borrowIssueAssetsMapper.insertSelective(asset);

            stateLog(str, "借用新增", "待发放", userId, userName, param.getBorrowUser());
        }

        //修改资产状为借用
        warehouseService.updateAssetState(param.getAssetIdList(), "待发放", null, null);

        //推送消息给借用人
        String[] asia = {param.getBorrowUserId()};
        String notification_title = "借用资产发放";
        String msg_title = "借用资产发放";
        String msg_content = "借用资产已发放，单号:"+ param.getNumber() +"请签字";
        log.info("借用资产发放,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

        //删除redis
        param.getAssetIdList().forEach(e->{
                redisUtil.delkey(e);
            }
        );
        return param ;
    }

    /**
     * 分页查询
     * @return
     */
    public List<BorrowIssueExtend> getAllPage(PageParams<SelPrams> param){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer i = reportMapper.selectUserIsAllDataAuth(userId);
        if(i==1){
            userId = null;
        }
        PageHelper.startPage(param.getCurrentPage(), param.getPerPageTotal());
        List<BorrowIssueExtend> list = borrowIssueMapper.getBorrowIssue(param.getParams().getStartDate(), param.getParams().getEndDate(), orgId, userId, null, null, null);
        if(list != null && list.size()>0){
            for (BorrowIssueExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),3);
                extend.setResults(results);
            }
        }
        return list;
    }

    /**
     * 查看
     * @param id
     * @return
     */
    public BorrowIssueExtend selById(String id){
        List<BorrowIssueExtend> list = borrowIssueMapper.getBorrowIssue(null, null, null, null, id, null, null);
        if(list != null && list.size()>0){
            for (BorrowIssueExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),3);
                extend.setResults(results);
            }
        }
        return list.get(0);
    }

    /**
     * 打印
     * @param ids
     * @return
     */
    public List<BorrowIssueExtend> print(String ids){
        List<BorrowIssueExtend> list = borrowIssueMapper.selByIds(Arrays.asList(ids.split(",")));
        if(list != null && list.size()>0){
            for (BorrowIssueExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),3);
                extend.setResults(results);
            }
        }
        return list;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public void delById(String id){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();


        //修改资产状为闲置
        List<String> list = borrowIssueMapper.getBorrowAssetId(id);
        list.stream().forEach(e1->{
            stateLog(e1, "借用删除", "闲置", userId, userName, "");
        });
        warehouseService.updateAssetState(list, "闲置", "", "");

        BorrowIssue bi = new BorrowIssue();
        bi.setId(id);
        bi.setIsDeleted(1);
        bi.setUpdateUser(userId);
        bi.setUpdateDate(TimeTool.getCurrentTimeStr());
        borrowIssueMapper.updateByPrimaryKeySelective(bi);

        BorrowIssue issue = borrowIssueMapper.selectByPrimaryKey(id);
        //推送消息给借用人
        String[] asia = {issue.getBorrowUserId()};
        String notification_title = "借用资产发放单删除";
        String msg_title = "借用资产发放单删除";
        String msg_content = "借用资产发放单删除, 单号:"+ issue.getNumber();
        log.info("借用资产发放单删除,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(msg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });
    }

    /**
     * 归还,可以批量
     * @param issue
     * @return
     */
    public void backById(BorrowIssue issue){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();
        Example example = new Example(BorrowIssue.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(issue.getId().split(",")));

        BorrowIssue bi = new BorrowIssue();
        bi.setBorrowBackState(2);
        bi.setActualBackDate(issue.getActualBackDate());
        bi.setBackUser(issue.getBackUser());
        bi.setUpdateUser(userId);
        bi.setUpdateDate(TimeTool.getCurrentTimeStr());
        borrowIssueMapper.updateByExampleSelective(bi, example);

        List<String> idsList = Arrays.asList(issue.getId().split(","));
        idsList.stream().forEach(e->{
            List<String> list = borrowIssueMapper.getBorrowAssetId(e);
            list.stream().forEach(e1->{
                stateLog(e1, "借用归还", "闲置", userId, userName, "");
            });
            //修改资产状为闲置
            warehouseService.updateAssetState(list, "闲置", "", "");

            BorrowIssue borrowIssue = borrowIssueMapper.selectByPrimaryKey(e);
            //推送消息给借用人
            if(borrowIssue != null && StringUtils.isNotBlank(borrowIssue.getBorrowUserId())){
                String[] asia = {borrowIssue.getBorrowUserId()};
                String notification_title = "借用资产归还";
                String msg_title = "借用资产归还";
                String msg_content = "借用资产归还, 单号:"+ borrowIssue.getNumber();
                log.info("借用资产归还,消息推送人："+ JSONObject.toJSONString(asia));
                JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
                Arrays.stream(asia).forEach(e1->{
                    PushManagement pu = new PushManagement();
                    pu.setCompanyId(orgId);
                    pu.setContent(msg_content);
                    pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    pu.setCuser(userId);
                    pu.setSender(e1);
                    pu.setResult(0);
                    pushMapper.insertSelective(pu);
                });
            }

        });

    }
    /**
     * 修改
     * @param param
     * @return
     */
    public void udpById(BorrowIssueExtend param){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        param.setUpdateUser(userId);
        param.setUpdateDate(TimeTool.getCurrentTimeStr());
        borrowIssueMapper.updateByPrimaryKeySelective(param);

        //修改之前资产状为闲置
        List<String> assetIds = borrowIssueMapper.getBorrowAssetId(param.getId());
        warehouseService.updateAssetState(assetIds, "闲置", "", "");

        //删除之前的资产，重新插入
        Example example = new Example(BorrowIssueAssets.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDeleted", 0);
        criteria.andEqualTo("borrowIssueId", param.getId());
        BorrowIssueAssets bas = new BorrowIssueAssets();
        bas.setUpdateUser(userId);
        bas.setUpdateDate(TimeTool.getCurrentTimeStr());
        bas.setIsDeleted(1);
        borrowIssueAssetsMapper.updateByExampleSelective(bas, example);
        Example example1 = new Example(WarehouseHistory.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("handerId", param.getId());
        historyMapper.deleteByExample(example1);


        historyMapper.batchInsert(param.getAssetIdList() ,param.getId(),3);
        //新增
        for (String str:param.getAssetIdList()) {

            if(!redisUtil.setnx(str,1800)){
                throw new LogicException("请核对资产状态是否发生改变");
            }

            BorrowIssueAssets asset = new BorrowIssueAssets();
            asset.setBorrowIssueId(param.getId());
            asset.setAssetId(str);
            asset.setIsDeleted(0);
            asset.setCreateUser(userId);
            asset.setCreateDate(TimeTool.getCurrentTimeStr());
            asset.setUpdateUser(userId);
            asset.setUpdateDate(TimeTool.getCurrentTimeStr());
            borrowIssueAssetsMapper.insertSelective(asset);

            stateLog(str, "借用修改", "待发放", userId, userName, param.getBorrowUser());

        }

        //修改资产状为待发放
        warehouseService.updateAssetState(param.getAssetIdList(), "待发放", "", "");

        //推送消息给借用人
        String[] asia = {param.getBorrowUserId()};
        String notification_title = "借用资产发放单修改";
        String msg_title = "借用资产发放单修改";
        String msg_content = "借用资产发放单修改，单号："+ param.getNumber() +"，请签字";
        log.info("借用资产发放单修改,消息推送人："+ JSONObject.toJSONString(asia));
        JpushClientUtil.sendToAsia(asia, notification_title, msg_title, msg_content,"");
        String finalMsg_content = msg_content;
        Arrays.stream(asia).forEach(e->{
            PushManagement pu = new PushManagement();
            pu.setCompanyId(orgId);
            pu.setContent(finalMsg_content);
            pu.setCtime(DateTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            pu.setCuser(userId);
            pu.setSender(e);
            pu.setResult(0);
            pushMapper.insertSelective(pu);
        });

        //删除redis
        param.getAssetIdList().forEach(e->{
                    redisUtil.delkey(e);
                }
        );
    }

    /**
     * 修改状态为已签字，2已签字
     */
    public void updState(SignatureParam param){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String userName = loginUser.getUserName();

        BorrowIssue issue= new BorrowIssue();
        issue.setId(param.getId());
        issue.setState(2);
        issue.setSignPic(param.getSignPic());
        borrowIssueMapper.updateByPrimaryKeySelective(issue);

        List<String> assetIds = borrowIssueMapper.getBorrowAssetId(param.getId());
        //日志记录
        assetIds.stream().forEach(e->{
            stateLog(e, "借用签字", "借用", userId, userName, null);

            String[] split = DateTools.dateToString(new Date(),"yyyy-MM-dd").split("-");
            AssetReport assetReport = new AssetReport();
            assetReport.setAssetId(e);
            assetReport.setArYear(split[0]);
            assetReport.setArMonth(split[1]);
            assetReport.setArDay(split[2]);
            assetReport.setUseType(2);
            assetReport.setUseUserId(userId);
            assetReportService.insertReport(assetReport);
        });

        //更新资产状态
        UserInfo user = assetReportMapper.selectUser(userId);

        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("assetId", assetIds);
        Warehouse warehouse = new Warehouse();
        warehouse.setState("借用");
        warehouse.setHandlerUser(userName);
        warehouse.setHandlerUserId(userId);
        warehouse.setUseCompany(user.getCompanyId());
        warehouse.setUseDepartment(user.getDeptId());
        warehouseMapper.updateByExampleSelective(warehouse, example);


        //更新审批单子表为已签字
        BorrowIssue borrowIssue = borrowIssueMapper.selectByPrimaryKey(param.getId());
        BorrowApplyAssets applyAssets = new BorrowApplyAssets();
        applyAssets.setId(borrowIssue.getApplyId());
        applyAssets.setState(4);
        borrowApplyAssetsMapper.updateByPrimaryKeySelective(applyAssets);

    }

    /**
     * 打印
     * @return
     */
    public List<BorrowIssueExtend> exportExcel(){
        List<BorrowIssueExtend> list = borrowIssueMapper.getBorrowIssue(null, null, null, null, null, null, null);
        if(list != null && list.size()>0){
            for (BorrowIssueExtend extend : list) {
                List<WarehouseHistoryResult> results = historyMapper.queryWarehouseHistory(extend.getId(),3);
                extend.setResults(results);
            }
        }
        return list;
    }

    /**
     * 资产处理日志
     * @param assetId
     * @param modelName
     * @param afterState
     * @param handlerUser
     * @param handlerUserId
     */
    public void stateLog(String assetId, String modelName, String afterState, String handlerUserId, String handlerUser, String borrowUser){
        Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetId);
        String logContent = "资产【"+warehouse.getAssetName()+"】"+ modelName +"处置；"
                + ChangLogUtil.simpleLogContxt(new LogContext("", warehouse.getHandlerUser(), borrowUser, warehouse.getState(),afterState));
        AssetLog assetLog = new AssetLog();
        assetLog.setAssetId(assetId);
        assetLog.setLogType("借用");
        assetLog.setHandlerId(handlerUserId);
        assetLog.setHandlerUser(handlerUser);
        assetLog.setHandlerContext(logContent);
        assetLog.setCreateUser(handlerUserId);
        assetLog.setCreateTime(TimeTool.getCurrentTimeStr());
        assetLogMapper.insertSelective(assetLog);
    }


}
